
package com.eva.android.widget;

import android.content.Context;
import android.os.Build;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.x52im.rbchat.R;

/**
 * 通用查询输入框UI组件实现类。
 *
 * @author Jack Jiang
 * @since 8.2
 */
public class SearchInputView extends FrameLayout {

    /** 文本输入框 */
    private EditText editView;
    /** 撤销输入小按钮 */
    private View cancelView;

    private SearchListener queryListener;

    public SearchInputView(@NonNull Context context) {
        this(context, null);
    }

    public SearchInputView(@NonNull Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SearchInputView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        inflate(getContext(), R.layout.search_input_view, this);
        cancelView = this.findViewById(R.id.search_input_view_cancel_search);
        cancelView.setOnClickListener(v -> editView.setText(""));
        editView = this.findViewById(R.id.search_input_view_editText);
        editView.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence txt, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence txt, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable txt) {
                search(txt.toString());
                handleCancelView(txt.toString());
            }
        });
    }

    private void search(String s) {
        if (queryListener != null) {
            queryListener.onSearchTextChange(s);
        }
    }

    private void handleCancelView(String s) {
        if (TextUtils.isEmpty(s)) {
            cancelView.setVisibility(View.GONE);
        } else {
            cancelView.setVisibility(View.VISIBLE);
        }
    }

    public void setKeyword(String s) {
        editView.setText(s);
        // 光标移到末尾
        WidgetUtils.setCursorToEnd(editView, false);
    }

    public void setOnQueryTextListener(SearchListener listener) {
        queryListener = listener;
    }

    public EditText getEditView(){
        return this.editView;
    }

//    public void setCursorToEnd(){
//        // 光标移动到尾部
//        editView.setSelection(editView.length());
//    }

    /**
     * 搜索内容改变监听器。
     */
    public interface SearchListener {
        void onSearchTextChange(String str);
    }
}
